import * as d3 from "d3";
import { RadarChart } from "./charts/radarChart.js";
import { ComboChart } from "./charts/comboChart.js";
import { WordCloud } from "./charts/wordCloud.js";
import { HeatMap } from "./charts/heatmap.js";
import data from "./assets/processed.csv";
import categorizedData from "./assets/categorized_questions.csv";

// 数据处理函数
function processData(rawData) {
    // 处理AI工具评分数据
    const toolData = processToolData(rawData);
    
    // 处理组合图数据（使用场景和满意度）
    const comboData = processComboData(rawData);
    
    // 处理频率数据
    const frequencyData = processFrequencyData(rawData);
    
    // 处理词云数据
    const wordCloudData = processWordCloudData(rawData);
    
    return {
        toolData,
        comboData,
        frequencyData,
        wordCloudData
    };
}

function processToolData(rawData) {
    const tools = ['chatgpt', 'wenxin', 'qianwen', 'doubao', 'kimi', 'deepseek'];
    const majors = ['文科类', '理科类', '工科类', '艺术类', '医学类'];
    
    return majors.map(major => {
        const majorData = rawData.filter(d => d.major === major);
        const scores = {};
        
        tools.forEach(tool => {
            const scoreColumn = `${tool}_score`;
            const validScores = majorData
                .map(d => d[scoreColumn])
                .filter(score => !isNaN(score));
                
            scores[tool] = validScores.length > 0 
                ? d3.mean(validScores) 
                : 0;
        });
        
        return {
            major: major,
            scores: scores
        };
    });
}

function processComboData(rawData) {
    const majors = ['文科类', '理科类', '工科类', '艺术类', '医学类'];
    const allScenarios = ['学术研究', '课程学习', '创意启发', '生活日常', '职业发展'];
    
    return majors.map(major => {
        const majorData = rawData.filter(d => d.major === major);
        
        // 计算该专业的场景选择总次数
        let totalSelections = 0;
        const scenarioCounts = {};
        
        allScenarios.forEach(scenario => {
            const count = majorData.filter(d => {
                try {
                    const scenarios = JSON.parse(d.usage_scenarios);
                    return scenarios.includes(scenario);
                } catch (e) {
                    return false;
                }
            }).length;
            
            scenarioCounts[scenario] = count;
            totalSelections += count;
        });
        
        // 处理满意度
        const satisfactionScore = {
            '非常满意': 5,
            '满意': 4,
            '一般': 3,
            '不满意': 2,
            '非常不满意': 1
        };
        
        const avgSatisfaction = d3.mean(
            majorData.map(d => satisfactionScore[d.satisfaction] || 0)
        );
        
        return {
            major,
            scenarios: scenarioCounts,
            satisfaction: avgSatisfaction || 0,
            total: majorData.length,
            totalSelections: totalSelections  // 新增：场景选择总次数
        };
    });
}

function processFrequencyData(rawData) {
    const majors = ['文科类', '理科类', '工科类', '艺术类', '医学类'];
    const frequencies = ['很少使用', '每月1-2次', '每周1-2次', '每周3-5次', '每天都用'];
    
    return majors.map(major => {
        const majorData = rawData.filter(d => d.major === major);
        const freqCounts = {};
        
        frequencies.forEach(freq => {
            freqCounts[freq] = majorData.filter(d => d.frequency === freq).length;
        });
        
        return {
            major,
            frequencies: freqCounts,
            total: majorData.length
        };
    });
}

function processWordCloudData(rawData) {
    // 直接返回分类数据，过滤掉待分类的项目
    return rawData.filter(d => d.category && d.category !== '待分类')
        .map(d => ({
            major: d.major,
            category: d.category
        }));
}

// 创建图表实例
const comboChart = new ComboChart('#combo-chart');
const radarChart = new RadarChart('#radar-chart');
const heatmapChart = new HeatMap('#heatmap-chart');
const wordCloud = new WordCloud('#wordcloud-chart');

// 加载数据后的初始化
function initCharts(data) {
    comboChart.update(data.comboData);
    radarChart.update(data.toolData);
    heatmapChart.update(data.frequencyData);
    wordCloud.update(data.wordCloudData);

    // 添加交互事件
    comboChart.on('majorHover', (major) => {
        heatmapChart.highlight(major);
        radarChart.highlight(major);
        wordCloud.renderWordCloud(major);
    });

    comboChart.on('majorOut', () => {
        heatmapChart.highlight(null);
        radarChart.highlight(null);
        wordCloud.renderWordCloud('所有专业');
    });
}

// 加载数据并初始化图表
Promise.all([
    d3.csv(data),
    d3.csv(categorizedData)
]).then(([rawData, categorizedQuestions]) => {
    console.log("原始数据总数:", rawData.length);
    
    // 数据预处理
    const cleanData = rawData.filter(d => {
        try {
            const scenarios = JSON.parse(d.usage_scenarios);
            return Array.isArray(scenarios) && scenarios.length > 0;
        } catch (e) {
            console.log("解析错误的数据:", d);
            return false;
        }
    });

    console.log("有效数据总数:", cleanData.length);

    // 处理数据
    const processedData = processData(cleanData);
    // 使用分类后的数据更新词云数据
    processedData.wordCloudData = processWordCloudData(categorizedQuestions);
    
    initCharts(processedData);
}).catch(error => {
    console.error('数据加载错误:', error);
});